package gwtappcontainer.server;

import gwtappcontainer.server.apps.APIException;
import gwtappcontainer.shared.apis.APIResponse.Status;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Logger;

import com.google.appengine.api.utils.SystemProperty;
import com.google.apphosting.api.ApiProxy;


public class Utils {   
	
	private static Logger logger = Logger.getLogger(Utils.class.getName());
       
    public static String getCloudSqlURL() throws RuntimeException {
           
        try {                  
            if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
                Class.forName("com.mysql.jdbc.GoogleDriver"); 
                
                String appId = ApiProxy.getCurrentEnvironment().getAppId();
                
                logger.info("appId = [" + appId + "]");
                
                if (appId.equals("s~ishaportaldev")) 
                	return "jdbc:google:mysql://ishaportalproject:ishaportaldev/ishaportal?user=root";
                if (appId.equals("s~ishaportaluat"))
                	return "jdbc:google:mysql://ishaportalproject:ishaportaluat/ishaportal?user=root";
                if (appId.equals("s~ishaportalstaging"))
                	return "jdbc:google:mysql://ishaportalproject:ishaportalstaging/ishaportal?user=root";
                if (appId.equals("s~ishaportal"))
                	return "jdbc:google:mysql://ishaportalproject:ishaportal/ishaportal?user=root";
                
                //wrong environment
                logger.warning("invalid appId [" + appId + "]");
                throw new APIException(Status.ERROR_RESOURCE_DOES_NOT_EXIST, 
                		"There is no cloud sql instance associated with app [" + appId + "]");
            }
           
            //dev environment                                              
            Class.forName("com.mysql.jdbc.Driver");
            if (null != System.getProperty("junittesting")) //junittesting
                return "jdbc:mysql://127.0.0.1:3306/ishaportaltest?user=root&password=admin";
                        
            return "jdbc:mysql://127.0.0.1:3306/ishaportal?user=root&password=admin";
            
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
       
    public static String getStackTraceAsString(Throwable e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
       
        return sw.toString();
    }                      

    public static boolean isValidEmail(String email) {
        return email.contains(" ") == false && email.matches(".+@.+\\.[a-z]+");
    }
    
    public static String toQuoted(String s) {
    	return "'" + s + "'";
    }
}

